package com.shangcheng.service;

import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shangcheng.entity.TCustomer;
import com.shangcheng.mapper.TCustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
public class TCustemerServiceImpl {
    @Value("${jwt.secretkey}")
    private String secret;
    @Autowired
    private TCustomerMapper customerDao;
    @Transactional(readOnly = true)
    public Page<TCustomer> pageCustomers(int page, int size) {
        Page<TCustomer> pagination = new Page<>(page, size); // 创建分页对象
        return customerDao.selectPage(pagination, null); // 查询分页数据
    }

    @Transactional(readOnly = true)
    public TCustomer queryByUsername(String username) {
        QueryWrapper<TCustomer> qw = new QueryWrapper<>();
        qw.eq("user_name", username);
        return customerDao.selectOne(qw);
    }


    public TCustomer register(TCustomer customer) {
        TCustomer newCustomer = new TCustomer();
        if(customer.getUserName()!="" && customer.getPassword()!="" && customer.getName()!="" && customer.getSex()!=null && customer.getAge()!=null && customer.getAddress()!="" && customer.getIdCard()!=""){
            newCustomer.setUserName(customer.getUserName());
            newCustomer.setPassword(customer.getPassword());
            newCustomer.setName(customer.getName());
            newCustomer.setSex(customer.getSex());
            newCustomer.setAge(customer.getAge());
            newCustomer.setAddress(customer.getAddress());
            newCustomer.setIdCard(customer.getIdCard());
            customerDao.insert(newCustomer);
            return newCustomer;
        }
        else {
            return newCustomer;
        }
    }

    public String createTocken(TCustomer customer) {
        Map<String, Object> headerMap = new HashMap<>();
        headerMap.put("alg", "HS256");
        headerMap.put("typ", "JWT");
        Map<String, Object> playLoad = new HashMap<>();
        playLoad.put("id", customer.getId());
        playLoad.put("username", customer.getUserName());
        playLoad.put("role", "custmer");
        playLoad.put("exp", String.valueOf(System.currentTimeMillis() + 86400000L));
        return JWTUtil.createToken(headerMap, playLoad, secret.getBytes());
    }

    // 更新用户信息
    @Transactional
    public void updateCustomer(TCustomer customer) {
        customerDao.updateById(customer);
    }
    @Transactional
    public void deleteCustomerById(Integer orderId) {
        customerDao.delete(new QueryWrapper<TCustomer>().eq("ID", orderId));
    }

}
